Page({
  data: {
    loading: true,
    hasRegistration: false,
    registration: {},
    statusText: '',
    statusColor: '',
    canRegister: false,
    canModify: false,
    submitTimeText: '',
    auditTimeText: ''
  },

  onLoad() {
    wx.setNavigationBarTitle({
      title: '注册状态'
    })
    
    this.loadRegistrationStatus()
  },

  onShow() {
    // 页面显示时刷新状态
    this.loadRegistrationStatus()
  },

  // 加载注册状态
  async loadRegistrationStatus() {
    this.setData({ loading: true })
    
    try {
      const result = await wx.cloud.callFunction({
        name: 'getUserRegistrationStatus',
        data: {}
      })
      
      if (result.result && result.result.success) {
        const data = result.result.data
        
        if (data.hasRegistration) {
          const registration = data.registration
          
          this.setData({
            hasRegistration: true,
            registration: registration,
            statusText: data.statusText,
            statusColor: data.statusColor,
            canRegister: data.canRegister,
            canModify: data.canModify,
            submitTimeText: this.formatTime(registration.submitTime),
            auditTimeText: registration.auditTime ? this.formatTime(registration.auditTime) : ''
          })
        } else {
          this.setData({
            hasRegistration: false,
            canRegister: true
          })
        }
      } else {
        throw new Error(result.result?.error || '获取状态失败')
      }
      
    } catch (error) {
      console.error('❌ 加载注册状态失败:', error)
      wx.showToast({
        title: '加载失败，请重试',
        icon: 'none'
      })
    } finally {
      this.setData({ loading: false })
    }
  },

  // 格式化时间
  formatTime(time) {
    if (!time) return ''
    
    const date = new Date(time)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    
    return `${year}-${month}-${day} ${hours}:${minutes}`
  },

  // 去注册
  goToRegister() {
    wx.showActionSheet({
      itemList: ['个人师傅注册', '施工公司注册'],
      success: (res) => {
        const type = res.tapIndex === 0 ? 'individual' : 'company'
        wx.navigateTo({
          url: `/pages/team-registration/team-registration?type=${type}`
        })
      }
    })
  },

  // 修改注册信息
  modifyRegistration() {
    const { registration } = this.data
    
    wx.showModal({
      title: '修改注册信息',
      content: '确定要修改注册信息吗？修改后将重新提交审核。',
      confirmText: '确定',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          wx.navigateTo({
            url: `/pages/team-registration/team-registration?type=${registration.type}&edit=true&id=${registration._id}`
          })
        }
      }
    })
  },

  // 刷新状态
  refreshStatus() {
    wx.showLoading({
      title: '刷新中...'
    })
    
    this.loadRegistrationStatus().finally(() => {
      wx.hideLoading()
      wx.showToast({
        title: '刷新完成',
        icon: 'success'
      })
    })
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadRegistrationStatus().finally(() => {
      wx.stopPullDownRefresh()
    })
  }
})
